import useToast from '@/hooks/useToast';
import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import type { TBody } from '@/types';
import type {
  ICreateSectionTagGroupBody,
  IDifference,
  IRemoveSectionTagGroupBody,
  ISectionDetails,
  ITag,
} from '@/interfaces';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { createSectionTagGroup, removeSectionTagGroup } from '@/services/api';
import diff from 'microdiff';
import {
  cleanFormData,
  getDiffData,
  getFilterData,
  isEmpty,
  isNum,
} from '@/lib/tool';

export default function UpdateSectionTagGroup(
  this: any,
  {
    details,
  }: {
    details: ISectionDetails;
  },
) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    id: string;
  }>({
    id: '',
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const [currentRemoveUserId, setCurrentRemoveUserId] = useState<
    number | undefined
  >();
  const queryClient = useQueryClient();

  const createSectionTagGroupMutation = useMutation(
    async (variables: TBody<ICreateSectionTagGroupBody>) => {
      await createSectionTagGroup(variables);
      await queryClient.invalidateQueries([
        '/forum',
        '/sections',
        details.basic.id,
        '/details',
      ]);
    },
  );
  const removeSectionTagGroupMutation = useMutation(
    async (variables: TBody<IRemoveSectionTagGroupBody>) => {
      await removeSectionTagGroup(variables);
      await queryClient.invalidateQueries([
        '/forum',
        '/sections',
        details.basic.id,
        '/details',
      ]);
    },
  );

  useEffect(() => {
    const differences = diff(
      {
        id: '',
      },
      {
        id: form.id,
      },
    );
    setDifferenceData(differences);
  }, [form]);

  function onChangeForm(e: ChangeEvent<HTMLSelectElement | HTMLInputElement>) {
    const name = e.target.name;
    const value = e.target.value;
    setForm({ ...form, [name]: value });
  }

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      checkForm();
      const body = getFilterData(getDiffData(differenceData));
      if (isEmpty(body)) {
        show({
          type: 'SUCCESS',
          message: '保存完成',
        });
        return;
      }

      await createSectionTagGroupMutation.mutateAsync({
        id: body.id,
        data: {
          sectionId: details.basic.id + '',
        },
      });

      clearData();
      show({
        type: 'SUCCESS',
        message: '保存完成',
      });
    } catch (e) {
      createSectionTagGroupMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  async function onClickRemove(item: ITag) {
    try {
      setCurrentRemoveUserId(item.id);

      await removeSectionTagGroupMutation.mutateAsync({
        id: item.id,
        data: {
          sectionId: details.basic.id + '',
        },
      });
      clearData();

      show({
        type: 'SUCCESS',
        message: '删除完成',
      });
    } catch (e) {
      removeSectionTagGroupMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function clearData() {
    setForm(cleanFormData(form));
    setDifferenceData([]);
    setCurrentRemoveUserId(undefined);
  }

  function checkForm() {
    const id = form.id;

    if (!id) {
      throw '标签组 Id 不能为空';
    }

    if (!isNum(id)) {
      throw '请正确输入标签组 Id';
    }
  }

  return (
    <div className="row">
      <div className="col">
        <div className="vstack gap-4">
          <div>
            <div className="table-responsive">
              <table className="table table-hover align-middle">
                <thead>
                  <tr className="text-nowrap">
                    <th scope="col" className="w-10 fw-normal">
                      ID
                    </th>
                    <th scope="col" className="w-10 fw-normal">
                      名称
                    </th>
                    <th scope="col" className="w-10"></th>
                  </tr>
                </thead>
                <tbody>
                  {(details.tagGroups || []).map((item) => {
                    return (
                      <tr key={item.id} className="text-nowrap">
                        <td>{item.id}</td>
                        <td>{item.name}</td>
                        <td>
                          <button
                            disabled={
                              currentRemoveUserId === item.id &&
                              removeSectionTagGroupMutation.isLoading
                            }
                            onClick={onClickRemove.bind(this, item)}
                            className="btn btn-sm btn-danger"
                            type="button"
                          >
                            {currentRemoveUserId === item.id &&
                            removeSectionTagGroupMutation.isLoading ? (
                              <span
                                className="spinner-border spinner-border-sm me-2"
                                role="status"
                                aria-hidden="true"
                              ></span>
                            ) : (
                              <i className="bi bi-trash me-2"></i>
                            )}
                            删除
                          </button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>

            {(details.tagGroups || []).length === 0 && (
              <div className="text-muted">暂无标签组</div>
            )}
          </div>

          <form onSubmit={onClickSave} className="vstack gap-4">
            <div>
              <label className="form-label">ID</label>
              <input
                type="text"
                className="form-control"
                name="id"
                value={form.id}
                onChange={onChangeForm}
                aria-describedby="id"
                placeholder="请输入标签组 Id"
              />
            </div>

            <button
              type="submit"
              disabled={createSectionTagGroupMutation.isLoading}
              className="btn btn-success w-25 my-4"
            >
              {createSectionTagGroupMutation.isLoading && (
                <span
                  className="spinner-border spinner-border-sm me-2"
                  role="status"
                  aria-hidden="true"
                ></span>
              )}
              更新
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}
